import {installModel} from '../../models';
import {getGuid16} from '../../units/extend';
import token from '../../units/token';
import {Router} from 'express';
import {mysql} from "../../config/dbHelper";

const router = Router();

//获取当前文件名称 __dirname=>当前文件所在的绝对路径 __filename当前文件的文件名,包括全路径
let fileName = __filename.replace(__dirname, "").replace('/', '').split('.')[0];
if (fileName.indexOf('\\') > -1) {
    fileName = fileName.replace(/\\/g, '');
}
//获取export 导出对象数据
const model = installModel(fileName);

/**
 * 获取所有的数据
 */
router.route('/getModuleList').post((req, res) => {
    let checkId = req.body["CheckId"];//用于验证Token的ID
    let checkToken = req.headers["token"];//验签
    if (!token.checkToken(checkToken, checkId)) {
        res.json({code: 2, msg: '验签验证失败!!'});
        return;
    }
    let whereList = JSON.parse(req.body["WhereList"]);
    model[fileName].query((qb) => {
        qb.select('*');
        whereList.forEach((item) => {
            let limitType = item["LimitType"];//查询类型 是where 还是 orWhere=>and or
            let symbol = item["Symbol"];//数学符号 '>'、'<'、'='、'<>'
            switch (item["KeyType"]) {
                case "firstLike"://%Value
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    break;
                case "lastLike"://Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', item["KeyValue"] + '%');
                    break;
                case "fullLike"://%Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    break;
                case "whereBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "whereNotBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "where":
                    if (limitType === 'where')
                        qb.where(item['KeyName'], symbol, item['KeyValue']);
                    else
                        qb.orWhere(item['KeyName'], symbol, item['KeyValue']);
                    break;
                case "whereIn":
                    if (limitType === 'where')
                        qb.whereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
                case "whereNotIn":
                    if (limitType === 'where')
                        qb.whereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
            }
        });
    }).fetchAll().then((result) => {
        if (result === null) {
            res.json({code: 0, msg: '查无数据'});
        } else {
            res.json({code: 1, msg: '信息获取成功', data: result})
        }
    }).catch((err) => {
        res.json({code: -1, msg: '数据获取失败，错误信息为=>' + err})
    });
});

/**
 * 获取所有的数据[分页]
 */
router.route('/getListInfoForPage').post((req, res) => {
    let checkId = req.body["CheckId"];//用于验证Token的ID
    let checkToken = req.headers["token"];//验签
    if (!token.checkToken(checkToken, checkId)) {
        res.json({code: 2, msg: '验签验证失败!!'});
        return;
    }
    let pageIndex = JSON.parse(req.body["PageIndex"]);
    let pageSize = JSON.parse(req.body["PageSize"]);
    let offset = (pageIndex - 1) * pageSize;

    let whereList = JSON.parse(req.body["WhereList"]);
    let listInfo = model[fileName].query((qb) => {
        qb.select('*');
        whereList.forEach((item) => {
            let limitType = item["LimitType"];//查询类型 是where 还是 orWhere=>and or
            let symbol = item["Symbol"];//数学符号 '>'、'<'、'='、'<>'
            switch (item["KeyType"]) {
                case "firstLike"://%Value
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    break;
                case "lastLike"://Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', item["KeyValue"] + '%');
                    break;
                case "fullLike"://%Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    break;
                case "whereBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "whereNotBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "where":
                    if (limitType === 'where')
                        qb.where(item['KeyName'], symbol, item['KeyValue']);
                    else
                        qb.orWhere(item['KeyName'], symbol, item['KeyValue']);
                    break;
                case "whereIn":
                    if (limitType === 'where')
                        qb.whereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
                case "whereNotIn":
                    if (limitType === 'where')
                        qb.whereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
            }
        });
        qb.limit(pageSize).offset(offset);
    });
    let countInfo = model[fileName].query((qb) => {
        qb.count('*', {as: 'Count'});
        whereList.forEach((item) => {
            let limitType = item["LimitType"];//查询类型 是where 还是 orWhere=>and or
            let symbol = item["Symbol"];//数学符号 '>'、'<'、'='、'<>'
            switch (item["KeyType"]) {
                case "firstLike"://%Value
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    break;
                case "lastLike"://Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', item["KeyValue"] + '%');
                    break;
                case "fullLike"://%Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    break;
                case "whereBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "whereNotBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "where":
                    if (limitType === 'where')
                        qb.where(item['KeyName'], symbol, item['KeyValue']);
                    else
                        qb.orWhere(item['KeyName'], symbol, item['KeyValue']);
                    break;
                case "whereIn":
                    if (limitType === 'where')
                        qb.whereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
                case "whereNotIn":
                    if (limitType === 'where')
                        qb.whereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
            }
        });
    });
    let Promise = require('bluebird');
    Promise.try(function () {
        return [
            listInfo.fetchAll().then((info) => {
                return info;
            }).catch((err) => {
                return err;
            }),
            countInfo.fetchAll().then((count) => {
                return count;
            }).catch((err) => {
                return err;
            }),
        ]
    }).all().then((result) => {
        result = JSON.parse(JSON.stringify(result));
        let returnData = result[0];
        let count = result[1][0].Count;
        let pageCount = Math.ceil(count / pageSize);
        res.json({
            code: 1, msg: '信息获取成功', data: {
                ReturnData: returnData,
                Count: count,
                PageCount: pageCount
            }
        })
    }).catch((err) => {
        res.json({code: -1, msg: '数据获取失败，错误信息为=>' + err})
    })
});


/**
 * 获取一条数据
 */
router.route('/getModule').post((req, res) => {
    let checkId = req.body["CheckId"];//用于验证Token的ID
    let checkToken = req.headers["token"];//验签
    if (!token.checkToken(checkToken, checkId)) {
        res.json({code: 2, msg: '验签验证失败!!'});
        return;
    }
    if (req.body["WhereList"] === undefined || req.body["WhereList"].length === 0) {
        res.json({code: -1, msg: '缺少必要参数'});
        return;
    }
    let whereList = JSON.parse(req.body["WhereList"]);
    if (whereList.length === 0) {
        res.json({code: -1, msg: '缺少必要参数'});
        return;
    }
    model[fileName].query((qb) => {
        qb.select('*');
        whereList.forEach((item) => {
            let limitType = item["LimitType"];//查询类型 是where 还是 orWhere=>and or
            let symbol = item["Symbol"];//数学符号 '>'、'<'、'='、'<>'
            switch (item["KeyType"]) {
                case "firstLike"://%Value
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"]);
                    break;
                case "lastLike"://Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', item["KeyValue"] + '%');
                    break;
                case "fullLike"://%Value%
                    if (limitType === 'where')
                        qb.where(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    else
                        qb.orWhere(item['KeyName'], 'like', '%' + item["KeyValue"] + '%');
                    break;
                case "whereBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "whereNotBetween"://between Value1 on Value2
                    if (limitType === 'where')
                        qb.whereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    else
                        qb.orWhereNotBetween(item['KeyName'], JSON.parse(item["KeyValue"]));
                    break;
                case "where":
                    if (limitType === 'where')
                        qb.where(item['KeyName'], symbol, item['KeyValue']);
                    else
                        qb.orWhere(item['KeyName'], symbol, item['KeyValue']);
                    break;
                case "whereIn":
                    if (limitType === 'where')
                        qb.whereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
                case "whereNotIn":
                    if (limitType === 'where')
                        qb.whereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    else
                        qb.orWhereNotIn(item['KeyName'], JSON.parse(item['KeyValue']));
                    break;
            }
        });
    }).fetch().then((result) => {
        if (result === null) {
            res.json({code: 0, msg: '查无数据'});
        } else {
            res.json({code: 1, msg: '信息获取成功', data: result})
        }
    }).catch((err) => {
        res.json({code: -1, msg: '数据获取失败，错误信息为=>' + err})
    });
});

/**
 * 新增数据
 */
router.route('/insert').post((req, res) => {
    let checkId = req.body["CheckId"];//用于验证Token的ID
    let checkToken = req.headers["token"];//验签
    if (!token.checkToken(checkToken, checkId)) {
        res.json({code: 2, msg: '验签验证失败!!'});
        return;
    }
    let jsonString = req.body["JsonString"];//需要新增的字段值对象，不包含时间类型
    let timeListStr = req.body["DateTimeList"];//需要创建的时间参数
    if (jsonString === undefined || jsonString.length === 0) {
        res.json({code: 0, msg: '非法操作'});
        return;
    }
    let jsonData = JSON.parse(jsonString);//将对象转换为数据
    let insertObj = {};//新增对象数据
    Object.keys(jsonData).forEach((keyName) => {
        if (!insertObj[keyName]) {
            if (keyName.toLowerCase() === "id")
                insertObj[keyName] = getGuid16();
            else
                insertObj[keyName] = jsonData[keyName];
        }
    });
    if (timeListStr !== undefined && timeListStr.length > 0) {
        let timeList = JSON.parse(timeListStr);
        timeList.forEach((keyName) => {
            if (!insertObj[keyName]) {
                insertObj[keyName] = new Date()
            }
        })
    }
    if (Object.keys(insertObj).length === 0) {
        res.json({code: -1, msg: '缺少必要参数'});
        return;
    }
    model[fileName].forge(insertObj).save(null, {method: 'insert'}).then((result) => {
        res.json({code: 1, msg: '操作成功'});
    }).catch((err) => {
        res.json({code: 0, msg: '操作失败，错误信息为=>' + err});
    })
});

/**
 * 更新数据
 */
router.route('/update').post((req, res) => {
    let checkId = req.body["CheckId"];//用于验证Token的ID
    let checkToken = req.headers["token"];//验签
    if (!token.checkToken(checkToken, checkId)) {
        res.json({code: 2, msg: '验签验证失败!!'});
        return;
    }
    let jsonString = req.body["JsonString"];//请求参数集
    let timeListStr = req.body["DateTimeList"];//需要创建的时间参数
    if (jsonString === undefined || jsonString.length === 0) {
        res.json({code: 0, msg: '非法操作'});
        return;
    }
    let jsonData = JSON.parse(jsonString);//将对象转换为数据
    let updateObj = {};//更新对象数据
    let whereObj = {};//限制条件对象
    Object.keys(jsonData).forEach((keyName) => {
        if (!updateObj[keyName]) {
            if (keyName.toLowerCase() === "id")
                whereObj[keyName] = jsonData[keyName];
            updateObj[keyName] = jsonData[keyName];
        }
    });
    if (timeListStr !== undefined && timeListStr.length > 0) {
        let timeList = JSON.parse(timeListStr);
        timeList.forEach((keyName) => {
            if (!updateObj[keyName]) {
                updateObj[keyName] = new Date()
            }
        })
    }
    if (Object.keys(updateObj).length === 0) {
        res.json({code: -1, msg: '缺少必要参数'});
        return;
    }
    model[fileName].forge().where(whereObj).save(updateObj, {patch: true}).then((result) => {
        res.json({code: 1, msg: '操作成功'});
    }).catch((err) => {
        res.json({code: 0, msg: '操作失败，错误信息为=>' + err});
    })
});


/**
 * 删除数据
 */
router.route('/remove').post((req, res) => {
    let checkId = req.body["CheckId"];//用于验证Token的ID
    let checkToken = req.headers["token"];//验签
    if (!token.checkToken(checkToken, checkId)) {
        res.json({code: 2, msg: '验签验证失败!!'});
        return;
    }
    let Id = req.body["Id"];//被删除的数据ID
    if (Id === undefined || Id.length === 0) {
        res.json({code: 0, msg: '非法操作'});
        return;
    }
    model[fileName].forge().where('id', '=', Id).destroy().then((result) => {
        res.json({code: 1, msg: '操作成功'});
    }).catch((err) => {
        res.json({code: 0, msg: '操作失败，错误信息为=>' + err});
    })
});

module.exports = router;
